<?php
declare (strict_types=1);

namespace app\common\tool\Ali;
use think\Exception;
use think\facade\Log;

/**
 * 阿里平台接口
 */
class Ali {
    private $AppKey = '203716613';
    private $AppSecret = '5ywofb4up1c8sgm6r5zut3gjyyag3v9n';
    private $AppCode = "ca994df88d3743aea61e6a0130742a58";

    public function __construct($AppKey=null, $AppSecret=null,$AppCode=null)
    {
        if ($AppKey) $this->AppKey = $AppKey;
        if ($AppSecret) $this->AppSecret = $AppSecret;
        if ($AppCode) $this->AppCode = $AppCode;
    }

    /**
     * 物流查询
     * @param $no
     * @param $type
     * @param $tel
     * @return array
     */
    public function expInfo($no,$type, $tel): array
    {
        error_reporting(E_ALL || ~E_NOTICE);
        $host = "https://wuliu.market.alicloudapi.com";//api访问链接
        $path = "/kdi";//API访问后缀
        $method = "GET";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $this->AppCode);

        if($type == 'SFEXPRESS'){
            $no .= ':'.substr($tel, -4);//快递单号 【顺丰和丰网请输入单号 : 收件人或寄件人手机号后四位。例如：123456789:1234】
        }
        $querys = "no={$no}&type={$type}";  //参数写在这里
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $result = $this->httpCurl($host, $url, $headers, $bodys, $method);

        if(isset($result['status']) && $result['status'] == '0'){/* status 0:正常查询 201:快递单号错误 203:快递公司不存在 204:快递公司识别失败 205:没有信息 207:该单号被限制，错误单号 */
            return ['code' => 1, 'msg' => 'ok', 'data' => $result['result']];
        }else{
            return ['code' => -1, 'msg' => $result['msg'], 'data' => $result['result']];
        }

    }

    /**
     * 查询快递公司
     * @return array
     */
    public function expressList(): array
    {
        error_reporting(E_ALL || ~E_NOTICE);
        $host = "http://wuliu.market.alicloudapi.com";
        $path = "/getExpressList";
        $method = "GET";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $this->AppCode);
        $querys = "";

        $bodys = "";
        $url = $host . $path . "?" . $querys;

        return $this->httpCurl($host, $url, $headers, $bodys, $method);

    }

    /**
     * @param $name
     * @param $idcard
     * @return array
     */
    public function realAuth($name, $idcard): array
    {
        error_reporting(E_ALL || ~E_NOTICE);
        $host = "https://idcert.market.alicloudapi.com";
        $path = "/idcard";
        $method = "GET";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $this->AppCode);
        //根据API的要求，定义相对应的Content-Type
        //array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "idCard={$idcard}&name=".urlencode($name);

        $bodys = "";
        $url = $host . $path . "?" . $querys;

        //成功：{"status":"01","msg":"实名认证通过！","idCard":"37************5916","name":"步*","sex":"男","area":"山东省邹城市","province":"山东省","city":"邹城市","prefecture":"","birthday":"1990-01-10","addrCode":"","lastCode":"","traceId":"20230208152258_5096ic_d73d4fc9"}
        //失败：{"status":"205","msg":"身份证格式不正确！","idCard":"37**********1559","name":"步*","sex":"","area":"","province":"","city":"","prefecture":"","birthday":"","addrCode":"","lastCode":"","traceId":"20230208152754_5230ic_e21a5828"}
        return $this->httpCurl($host, $url, $headers, $bodys, $method);
    }

    /**
     * @param $host
     * @param $url
     * @param $headers
     * @param $bodys
     * @param string $method
     * @return string
     */
    private function httpCurl($host,$url,$headers,$bodys,$method='GET'): array
    {
        try{
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_FAILONERROR, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HEADER, true);
            if (1 == strpos("$".$host, "https://"))
            {
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            }
            curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);

            $out_put = curl_exec($curl);

            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

            list($header, $body) = explode("\r\n\r\n", $out_put, 2);
            if ($httpCode == 200) {
                return json_decode($body,true);
            } else {
                if ($httpCode == 400 && strpos($header, "Invalid Param Location") !== false) {
                    Log::write("参数错误");
                } elseif ($httpCode == 400 && strpos($header, "Invalid AppCode") !== false) {
                    Log::write("AppCode错误");
                } elseif ($httpCode == 400 && strpos($header, "Invalid Url") !== false) {
                    Log::write("请求的 Method、Path 或者环境错误");
                } elseif ($httpCode == 403 && strpos($header, "Unauthorized") !== false) {
                    Log::write("服务未被授权（或URL和Path不正确）");
                } elseif ($httpCode == 403 && strpos($header, "Quota Exhausted") !== false) {
                    Log::write("套餐包次数用完");
                } elseif ($httpCode == 403 && strpos($header, "Api Market Subscription quota exhausted") !== false) {
                    Log::write("套餐包次数用完，请续购套餐");
                } elseif ($httpCode == 500) {
                    Log::write("API网关错误");
                } elseif ($httpCode == 0) {
                    Log::write("URL错误");
                } else {
                    Log::write("参数名错误 或 其他错误");
                    Log::write($httpCode);
                    $headers = explode("\r\n", $header);
                    $headList = array();
                    foreach ($headers as $head) {
                        $value = explode(':', $head);
                        $headList[$value[0]] = $value[1];
                    }
                    Log::write($headList['x-ca-error-message']);
                }

                return ['code' => -1, 'msg'=>'服务器错误！'];
            }

        }catch (\Exception $e){
            Log::write("Ali：".$e->getMessage());
            return ['code' => -1, 'msg'=>$e->getMessage()];
        }

    }

}
